/*TCP client program using Berkley Sockets*/

/*Compile command: cc -o tcpc tcpc.c -lnsl -lsocket*/
/*Run Command: ./tcpc localhost */

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>	// exit function	
#include<string.h>

#define SERVER_PORT 5488
#define MAX_LINE 256

int main (int argc,char * argv[])
{
	FILE *fp;
	struct hostent *hp; 
	struct sockaddr_in sin;
	char *host;
	char buf[MAX_LINE];
	int s;
	int len=0;

	if (argc==2)
	{
		host = argv[1];
	}
	else
	{
		fprintf(stderr,"usage:simplex-talk host error\n");
		exit(1);
	}

	// This function grabs the host by name. Simply put, if
	// you pass in 'localhost' then ypu will get back
	// 127.0.0.1
	hp = gethostbyname(host);
	if (!hp)
	{
		fprintf(stderr,"simplex-talk:unknown host: %s\n",host);
		exit(1);
	}

	// this clears the buffer
	bzero((char *)&sin, sizeof(sin));
	// AF_INET is the address family 
	sin.sin_family = AF_INET;
	bcopy(hp->h_addr, (char *)&sin.sin_addr,hp->h_length);
	// the server port
	sin.sin_port = htons(SERVER_PORT);
	
	// socket allows us to grab a socket to work with.
	// if the return is less than zero than this for
	// whatever reason failed.
	if ((s = socket(PF_INET, SOCK_STREAM,0)) < 0)
	{
		perror("simplex_talk: socket error");
		exit(1);
	}
	
	// Connect to the address
	if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
	{
		perror("simplex_talk: connect error");
		close(s);
		exit(1);
	}
	
	// This section grabs strings from the command line
	// and sends them over the connection
	while (fgets(buf, sizeof(buf), stdin))
	{
		buf[MAX_LINE-1] = '\0';
		len = strlen(buf) + 1;
		send(s, buf, len, 0);
	}
}
